package com.example.chapter06.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtil {
    //把字符串保存到指定路径的文本文件
    public static void saveText(String path, String text) throws IOException {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(path));
            bw.write(text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    }

    //从指定路径的文本文件读取内容字符串

    public static String openText(String path) throws IOException {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = new BufferedReader(new FileReader(path));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            Log.e("liu", "错误");
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return sb.toString();
    }

    //把位图数据保存到指定路径
    public static void saveImage(String path, Bitmap bitmap) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(path)) {
            //把位图数据压缩到文件输出流中
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    //从指定路径的图片文件当中读取位图数据
    public static Bitmap openImage(String path) throws IOException {
        Bitmap bitmap = null;
        try (FileInputStream fis = new FileInputStream(path)) {
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        return bitmap;
    }
}
